package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.util.SensitiveWordUtil;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojo.ApArticle;
import com.usian.model.article.pojo.ApArticleConfig;
import com.usian.model.article.pojo.ApArticleContent;
import com.usian.model.article.pojo.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.pojos.WmNews;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AutoScanMeaiaNewsIdImpl implements WemediaNewsAutoScanService {
    @Resource
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Resource
    private GreenImageScan greenImageScan;
    @Autowired
    private GreeTextScan greeTextScan;
    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Resource
    private FastDFSClient fastDFSClient;
    @Autowired
    private AdSensitiveService adSensitiveService;
    @Override
    public void autoScanMeaiaNewsId(Integer id) {
        //1.根据id查询文章信息
        ResponseResult news = wemediaFeign.findByIdNews(id);
        //2.判断文章news的状态
        WmNews data = (WmNews) news.getData();
        //当前状态为4  人工通过
        if (data.getStatus() == 4) {
            //保存数据即可 给article的3个表添加数据  ap_article'\ ap_article_config'\ ap_article_content
            //编写保存文件数据的方法
            saveArticleAll(data);
        }

        //date对象转换成毫秒值
        if (data.getStatus() == 8 && data.getPublishTime().getTime() >= System.currentTimeMillis()) {
            saveArticle(data);
            return;
        }

/*  状态为1
  自动审核----->阿里云------>审核 文本 图片 pass block review
   1.提取文本和图片
   2.内部算法进行审核---->审核通过

   4.调用阿里云的图片审核工具进行审核   flag=0
1. 查询文章中的文本是否有敏感词库中关键字  审核不通过  flag=0
   6.返回结果  根据 自动审核的结果来判断
        果三种审核的flag都为0说明审核 通过 保存文章数据
       如果三种审核的flag都为0 说明审核通过  保存文章数据 3表 修改文章的状态为
        返回的审核结果需要人工审核  修改文章的状态更改为3
*/
//   3.0调用阿里云的文本审核工具类进行审核   flag=0
         if (data.getStatus()==1){

         }
    }
    //敏感词
    public boolean wordScan(WmNews wmNews){
        boolean falg=true;
        List<AdSensitive> list = adSensitiveService.findAll();
        //提取list集合中的敏感词
        List<String> word=new ArrayList<>();
        for (AdSensitive adSensitive : list) {
            word.add(adSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(word);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(getContent(wmNews));
        if (map.size()>0){
            //查找敏感词汇
            //说明不审核通过
            falg=false;
            wmNews.setStatus(2);
            wmNews.setReason("审核不通过有敏感词汇");
            //修改文章中的内容
            wemediaFeign.updateWmNews(wmNews);
        }
        return falg;
    }

    //---------------------------
    //审核图片
    public boolean imageScan(List<String> images,WmNews wmNews) throws Exception {
        boolean falg=true;
        Integer status=0;
        String msg="";
        List<byte[]> imageList = new ArrayList<>();

            for (String image:images){
                String imageName = image.replace(fileServerUrl, "");
                int index = imageName.indexOf("/");
                String groupName = imageName.substring(0, index);
                String imagePath = imageName.substring(index + 1);
                byte[] imageByte = fastDFSClient.download(groupName, imagePath);
                imageList.add(imageByte);
            }
        Map map = greenImageScan.imageScan(imageList);
        String result =(String) map.get("suggestion");
          if (result.equals("block")){
              status=2;
              msg="审核不通过图片有敏感内容";
              falg=false;
          }else if (result.equals("review")){
              status=3;
              msg="图片不确定 人工审核";
              falg=false;
          }
          wmNews.setStatus(status);
          wmNews.setReason(msg);
          //修改文章中的内容
          if (falg){
            wemediaFeign.updateStatusAndReason(wmNews);
        }
          return falg;
    }
    //审核文字的功能
    public boolean textScan(String str) throws Exception {
        boolean falg=true;
        WmNews wmNews = new WmNews();
        Integer status=0;
        String msg="";
        Map map = greeTextScan.greeTextScan(str);
        String result=(String) map.get("suggestion");
        if (result.equals("review")){
            status=3;
            msg="内容不确定 人工审核";
            falg=false;
        }else  if(result.equals("block")){
            //说明不审核通过
            status=2;
            msg="审核不通过有敏感词汇";
            falg=false;
        }
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        //远程调用修改
        //修改文章中的内容
        if (falg){
            wemediaFeign.updateStatusAndReason(wmNews);
        }
         return falg;
    }
    //从data中取出文本图片
    public String getContent(WmNews wmNews){
        String str="";
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("text")){
                 str =(String) map.get("value");
            }
        }
        return str;
    }

    //
    public List<String> getImage(WmNews wmNews){
        List<String> list=new ArrayList<>();
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                 list.add(map.get("value").toString());
            }
        }
        return list;
    }
    //保存article
    //融合方法
    public void saveArticleAll(WmNews wmNews){
        ApArticle apArticle = saveArticle(wmNews);
        saveApArticleContent(wmNews,apArticle);
        saveArticleConfig(wmNews,apArticle);
    }
    public ApArticle saveArticle(WmNews wmNews){
        ApArticle apArticle = new ApArticle();
        apArticle.setChannelId(wmNews.getChannelId());
        apArticle.setImages(wmNews.getImages());
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        //通过远程调用feign获取作者的信息
        ApAuthor apAuthor = articleFeign.findByUserId(wmNews.getUserId());
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        apArticle.setCreatedTime(apArticle.getCreatedTime());
        apArticle.setPublishTime(apArticle.getPublishTime());
        //保存
        articleFeign.saveApArticle(apArticle);
        return apArticle;
    }
    //保存ap_article_config
    public void saveArticleConfig(WmNews wmNews,ApArticle apArticle){
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());
        config.setIsDown(wmNews.getEnable()==1?true:false);
        config.setIsDelete(false);
        config.setIsForward(false);
        config.setIsComment(true);
        ResponseResult result = articleFeign.saveApArticleConfig(config);
    }
    //保存ap_article_content
    public void saveApArticleContent(WmNews wmNews,ApArticle apArticle){
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(wmNews.getContent());
        ResponseResult result = articleFeign.saveApArticleContent(content);
    }
}
